#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import time
from datetime import datetime

class MainWindow:
    def __init__(self, game_manager):
        self.game_manager = game_manager
        self.root = tk.Tk()
        self.setup_window()
        self.create_widgets()
        self.update_timer = None
        self.start_update_loop()
        
    def setup_window(self):
        """设置主窗口"""
        self.root.title("VX Battle - 微信小游戏")
        self.root.geometry("800x600")
        self.root.resizable(True, True)
        
        # 设置窗口图标和样式
        self.root.configure(bg='#f0f0f0')
        
        # 设置样式
        style = ttk.Style()
        style.theme_use('clam')
        
        # 自定义样式
        style.configure('Title.TLabel', font=('Arial', 16, 'bold'), background='#f0f0f0')
        style.configure('Header.TLabel', font=('Arial', 12, 'bold'), background='#f0f0f0')
        style.configure('Info.TLabel', font=('Arial', 10), background='#f0f0f0')
        style.configure('Action.TButton', font=('Arial', 10, 'bold'))
        
    def create_widgets(self):
        """创建界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="VX BATTLE", style='Title.TLabel')
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 10))
        
        subtitle_label = ttk.Label(main_frame, text="微信小游戏原型", style='Header.TLabel')
        subtitle_label.grid(row=1, column=0, columnspan=2, pady=(0, 20))
        
        # 左侧面板 - 角色信息
        self.create_character_panel(main_frame)
        
        # 右侧面板 - 功能按钮
        self.create_action_panel(main_frame)
        
        # 底部状态栏
        self.create_status_bar(main_frame)
        
    def create_character_panel(self, parent):
        """创建角色信息面板"""
        char_frame = ttk.LabelFrame(parent, text="角色信息", padding="10")
        char_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 10))
        
        # 角色基本信息
        self.char_name_label = ttk.Label(char_frame, text="未选择角色", style='Header.TLabel')
        self.char_name_label.grid(row=0, column=0, columnspan=2, sticky=tk.W, pady=(0, 5))
        
        self.char_class_label = ttk.Label(char_frame, text="", style='Info.TLabel')
        self.char_class_label.grid(row=1, column=0, columnspan=2, sticky=tk.W, pady=(0, 10))
        
        # 属性信息
        ttk.Label(char_frame, text="等级:", style='Info.TLabel').grid(row=2, column=0, sticky=tk.W)
        self.level_label = ttk.Label(char_frame, text="-", style='Info.TLabel')
        self.level_label.grid(row=2, column=1, sticky=tk.W)
        
        ttk.Label(char_frame, text="生命值:", style='Info.TLabel').grid(row=3, column=0, sticky=tk.W)
        self.hp_label = ttk.Label(char_frame, text="-/-", style='Info.TLabel')
        self.hp_label.grid(row=3, column=1, sticky=tk.W)
        
        ttk.Label(char_frame, text="魔法值:", style='Info.TLabel').grid(row=4, column=0, sticky=tk.W)
        self.mp_label = ttk.Label(char_frame, text="-/-", style='Info.TLabel')
        self.mp_label.grid(row=4, column=1, sticky=tk.W)
        
        ttk.Label(char_frame, text="经验值:", style='Info.TLabel').grid(row=5, column=0, sticky=tk.W)
        self.exp_label = ttk.Label(char_frame, text="-/-", style='Info.TLabel')
        self.exp_label.grid(row=5, column=1, sticky=tk.W)
        
        # 经验条
        self.exp_progress = ttk.Progressbar(char_frame, mode='determinate')
        self.exp_progress.grid(row=6, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(5, 10))
        
        # 状态信息
        ttk.Label(char_frame, text="状态:", style='Info.TLabel').grid(row=7, column=0, sticky=tk.W)
        self.status_label = ttk.Label(char_frame, text="空闲", style='Info.TLabel')
        self.status_label.grid(row=7, column=1, sticky=tk.W)
        
        # 挂机信息
        self.idle_info_label = ttk.Label(char_frame, text="", style='Info.TLabel')
        self.idle_info_label.grid(row=8, column=0, columnspan=2, sticky=tk.W, pady=(5, 0))
        
    def create_action_panel(self, parent):
        """创建功能按钮面板"""
        action_frame = ttk.LabelFrame(parent, text="游戏功能", padding="10")
        action_frame.grid(row=2, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 按钮样式配置
        button_width = 20
        button_pady = 5
        
        # 角色管理按钮
        char_btn = ttk.Button(action_frame, text="角色管理", 
                             command=self.open_character_manager, 
                             style='Action.TButton', width=button_width)
        char_btn.grid(row=0, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 挂机系统按钮
        idle_btn = ttk.Button(action_frame, text="挂机系统", 
                             command=self.open_idle_system, 
                             style='Action.TButton', width=button_width)
        idle_btn.grid(row=1, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 战斗系统按钮
        battle_btn = ttk.Button(action_frame, text="战斗系统", 
                               command=self.open_battle_system, 
                               style='Action.TButton', width=button_width)
        battle_btn.grid(row=2, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 游戏统计按钮
        stats_btn = ttk.Button(action_frame, text="游戏统计", 
                              command=self.show_game_stats, 
                              style='Action.TButton', width=button_width)
        stats_btn.grid(row=3, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 分隔线
        separator = ttk.Separator(action_frame, orient='horizontal')
        separator.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=10)
        
        # 保存游戏按钮
        save_btn = ttk.Button(action_frame, text="保存游戏", 
                             command=self.save_game, 
                             style='Action.TButton', width=button_width)
        save_btn.grid(row=5, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 退出游戏按钮
        exit_btn = ttk.Button(action_frame, text="退出游戏", 
                             command=self.exit_game, 
                             style='Action.TButton', width=button_width)
        exit_btn.grid(row=6, column=0, pady=button_pady, sticky=(tk.W, tk.E))
        
        # 配置列权重
        action_frame.columnconfigure(0, weight=1)
        
    def create_status_bar(self, parent):
        """创建状态栏"""
        status_frame = ttk.Frame(parent)
        status_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(10, 0))
        
        self.status_text = ttk.Label(status_frame, text="就绪", style='Info.TLabel')
        self.status_text.grid(row=0, column=0, sticky=tk.W)
        
        self.time_label = ttk.Label(status_frame, text="", style='Info.TLabel')
        self.time_label.grid(row=0, column=1, sticky=tk.E)
        
        status_frame.columnconfigure(1, weight=1)
        
    def update_character_info(self):
        """更新角色信息显示"""
        current_char = self.game_manager.get_current_character()
        
        if current_char:
            # 更新基本信息
            self.char_name_label.config(text=f"{current_char.name}")
            self.char_class_label.config(text=f"Lv.{current_char.level} {current_char.character_class}")
            
            # 更新属性
            self.level_label.config(text=str(current_char.level))
            self.hp_label.config(text=f"{current_char.hp}/{current_char.max_hp}")
            self.mp_label.config(text=f"{current_char.mp}/{current_char.max_mp}")
            self.exp_label.config(text=f"{current_char.exp}/{current_char.exp_to_next_level}")
            
            # 更新经验条
            exp_percentage = (current_char.exp / current_char.exp_to_next_level) * 100
            self.exp_progress['value'] = exp_percentage
            
            # 更新状态
            if current_char.is_idle:
                idle_duration = time.time() - current_char.idle_start_time
                hours = int(idle_duration // 3600)
                minutes = int((idle_duration % 3600) // 60)
                self.status_label.config(text=f"挂机中")
                self.idle_info_label.config(text=f"地点: {current_char.idle_location}\n时间: {hours}h {minutes}m")
            elif current_char.is_in_battle:
                self.status_label.config(text="战斗中")
                self.idle_info_label.config(text=f"战斗ID: {current_char.battle_id}")
            else:
                self.status_label.config(text="空闲")
                self.idle_info_label.config(text="")
        else:
            # 没有选择角色
            self.char_name_label.config(text="未选择角色")
            self.char_class_label.config(text="请先创建或选择一个角色")
            self.level_label.config(text="-")
            self.hp_label.config(text="-/-")
            self.mp_label.config(text="-/-")
            self.exp_label.config(text="-/-")
            self.exp_progress['value'] = 0
            self.status_label.config(text="无角色")
            self.idle_info_label.config(text="")
            
    def update_time_display(self):
        """更新时间显示"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.config(text=current_time)
        
    def start_update_loop(self):
        """启动更新循环"""
        def update_loop():
            self.update_character_info()
            self.update_time_display()
            self.update_timer = self.root.after(1000, update_loop)  # 每秒更新一次
            
        update_loop()
        
    def open_character_manager(self):
        """打开角色管理窗口"""
        from .character_window import CharacterWindow
        CharacterWindow(self.root, self.game_manager)
        
    def open_idle_system(self):
        """打开挂机系统窗口"""
        current_char = self.game_manager.get_current_character()
        if not current_char:
            messagebox.showwarning("警告", "请先选择一个角色！")
            return
            
        from .idle_window import IdleWindow
        IdleWindow(self.root, self.game_manager)
        
    def open_battle_system(self):
        """打开战斗系统窗口"""
        current_char = self.game_manager.get_current_character()
        if not current_char:
            messagebox.showwarning("警告", "请先选择一个角色！")
            return
            
        from .battle_window import BattleWindow
        BattleWindow(self.root, self.game_manager)
        
    def show_game_stats(self):
        """显示游戏统计"""
        stats = self.game_manager.get_game_stats()
        character_stats = stats.get('character_stats', {})
        
        stats_text = f"""游戏统计信息
        
角色统计:
  总角色数: {character_stats.get('total_characters', 0)}
  最高等级: {character_stats.get('max_level', 0)}
  
职业分布:"""
        
        for class_name, count in character_stats.get('class_distribution', {}).items():
            stats_text += f"\n  {class_name}: {count}个"
            
        messagebox.showinfo("游戏统计", stats_text)
        
    def save_game(self):
        """保存游戏"""
        try:
            self.game_manager.save_game()
            self.status_text.config(text="游戏已保存")
            messagebox.showinfo("保存成功", "游戏数据已保存！")
        except Exception as e:
            messagebox.showerror("保存失败", f"保存游戏时出错: {str(e)}")
            
    def exit_game(self):
        """退出游戏"""
        result = messagebox.askyesnocancel("退出游戏", "是否保存游戏后退出？")
        
        if result is True:  # 保存并退出
            try:
                self.game_manager.save_game()
                messagebox.showinfo("退出", "游戏已保存，感谢游玩！")
                self.quit()
            except Exception as e:
                messagebox.showerror("保存失败", f"保存游戏时出错: {str(e)}")
        elif result is False:  # 直接退出
            if messagebox.askokcancel("确认退出", "确定不保存直接退出吗？"):
                self.quit()
        # result is None 表示取消，不做任何操作
        
    def quit(self):
        """退出应用"""
        if self.update_timer:
            self.root.after_cancel(self.update_timer)
        self.root.quit()
        self.root.destroy()
        
    def run(self):
        """运行主窗口"""
        self.root.protocol("WM_DELETE_WINDOW", self.exit_game)
        self.root.mainloop()